package com.xucia.jsponic;

import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.ScriptRuntime;
import org.mozilla.javascript.ScriptableObject;

import com.xucia.jsponic.data.GlobalData;
import com.xucia.jsponic.data.Identification;
import com.xucia.jsponic.data.ObjectId;
import com.xucia.jsponic.data.Persistable;
import com.xucia.jsponic.data.Templates;

public class JsponicRuntime {
	public static NativeObject newObject() {
        NativeObject result = new NativeObject();
        ScriptRuntime.setObjectProtoAndParent(result, GlobalData.getGlobalScope());
        return result;	
	}
	public static Persistable newObject(ObjectId basis) {
		Class<? extends Persistable> clazz = null;
		if (basis != null) 
			clazz = Templates.getClassForObject(basis);
		Persistable result;
		if (clazz !=null)
			try {
				result =  clazz.newInstance();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		else
			result = new NativeObject();
        ScriptRuntime.setObjectProtoAndParent((ScriptableObject) result, GlobalData.getGlobalScope());
        if (basis != null)
        	result.setPrototype(basis.getTarget());
        return result;	
	}
	public static NativeArray newArray() {
        NativeArray result = new NativeArray(0);
        ScriptRuntime.setObjectProtoAndParent(result, GlobalData.getGlobalScope());
        return result;
	}
	public static Object load(String id) {
		return Identification.idForString(id).getTarget();
	}
}
